#include "dir.h"

int handle_cd(session_t *session, int netfd, MYSQL *mysql, const char*destDir){
    char buf[1024] = {0};

    int destDirID = -1;
    char query[MAX_QUERY_LEN] = {0};
    
    if(destDir == NULL||strlen(destDir) == 0){
        //cd 无参数时 返回根目录
        bzero(query, sizeof(query));
        sprintf(query,
                "select id from file where username = '%s' and parent_id = -1 and tomb = 0",
                session->username);
        int ret = mysql_query(mysql, query);
        MYSQL_QUERY_CHECK(ret, mysql);
        
        MYSQL_RES *table = mysql_store_result(mysql);
        MYSQL_STORE_RESULT_CHECK(table, mysql);

        MYSQL_ROW row = mysql_fetch_row(table);
        //更新session
        session->curDirID = atoi(row[0]);
        strncpy(session->curVirPath, "/", sizeof(session->curVirPath)-1);
        
        sendtlv(netfd, buf);        
        return 0;
    }
    //cd 有参数
    int ret = make_id_path(session, mysql, destDir, &destDirID);
    if(ret != 0){
        //不存在 不是目录
        strncpy(buf, "参数错误.", sizeof(buf)-1);
        sendtlv(netfd, buf);        
        return -1;
    }
    
    //已拿到目标目录id -> select目标目录path
    bzero(query, sizeof(query));
    sprintf(query,
            "select path from file where username = '%s' and id = %d and tomb = 0",
            session->username, destDirID);
    ret = mysql_query(mysql, query);
    MYSQL_QUERY_CHECK(ret, mysql);

    MYSQL_RES *table = mysql_store_result(mysql);
    MYSQL_STORE_RESULT_CHECK(table, mysql);

    MYSQL_ROW row = mysql_fetch_row(table);
    //更新session
    session->curDirID = destDirID;
    strncpy(session->curVirPath, row[0], sizeof(session->curVirPath)-1);
    strncpy(buf, "cd成功.", sizeof(buf)-1); 
    sendtlv(netfd, buf);        
    return 0;
}
